﻿#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Lokad.Monitoring.Persistence.Serialization;

namespace Lokad.Monitoring.Rsm
{
    public class RsmClient
    {
        public RsmDocument Open(string url, string basicAuthInfo)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            // adding option Basic Auth credentials
            if(null != basicAuthInfo)
            {
                var authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(basicAuthInfo));
                request.Headers["Authorization"] = "Basic " + authInfo;
            }

            var response = request.GetResponse();

            var serializer = new PoxSerializer(typeof (RsmDocument));
            var doc = serializer.ReadObject(response.GetResponseStream()) as RsmDocument;

            // enforcing non-null values
            if(null == doc.Messages) doc.Messages = new List<Message>();
            if(null == doc.Indicators) doc.Indicators = new List<Indicator>();

            return doc;
        }
    }
}
